
from django.shortcuts import render,redirect
from app01.utils.pagination import Pagination
from app01.utils.form import UserForm
from app01 import models

def user_list(request):
    queryset = models.UserInfo.objects.all()

    page_object = Pagination(request,queryset)
    context = {
        "queryset":page_object.page_queryset,
        "page_string":page_object.html()
    }

    return render(request,'user_list.html',context)


def user_add(request):
    context = {
        "gender_choices": models.UserInfo.gender_choices,
        "depart_list": models.Department.objects.all()
    }
    if request.method == 'GET':
        return render(request,'user_add.html',context)

    # 获取前端提交的数据
    name = request.POST.get('name')
    password = request.POST.get('password')
    age = request.POST.get('age')
    gender = request.POST.get('gender')
    account = request.POST.get('account')
    createTime = request.POST.get('create_time')
    depart = request.POST.get('depart')

    # 添加到数据库
    models.UserInfo.objects.create(name=name,password=password,age=age,account=account,create_time=createTime,gender=gender,depart_id=depart)
    # 返回到用户列表页面
    return redirect('/user/list')



def user_form_add(request):
    """添加用户（ModelForm版本）"""
    if request.method == "GET":
        form = UserForm()
        return render(request,"user_form_add.html",{"form":form})
    # 用户POST提交数据，数据校验
    form = UserForm(data=request.POST)
    if form.is_valid(): # 校验用户提交的数据是否合法
        form.save()
        return redirect('/user/list')
    # 如何不合法
    return render(request,'user_form_add.html',{'form':form})

def user_form_edit(request,nid):
    if request.method == 'GET':
        # 根据ID去数据库获取要编辑的数据
        row_object = models.UserInfo.objects.filter(id= nid).first()
        form = UserForm(instance=row_object)
        return render(request,'user_edit.html',{'form':form})

    row_object = models.UserInfo.objects.filter(id= nid).first()
    form = UserForm(data=request.POST,instance=row_object)
    if form.is_valid(): # 校验用户提交的数据是否合法
        form.save()
        return redirect('/user/list')
    return render(request,'user_edit.html',{'form':form})

def user_form_delete(request,nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list')

